package com.warrior.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.warrior.configer.ConfigHelper;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Map;

/**
 * 微信授权组件
 * Created by Shawn on 2017/3/24.
 */
public class WxChatAuthTools {

    public WxChatAuthTools() {
    }

    private static final String WX_URL = ConfigHelper.getConfig().getString("WX.GETCODE.URL");

    private static final String APP_ID = ConfigHelper.getConfig().getString("WX.APP.ID");

    private static String redirect_uri = ConfigHelper.getConfig().getString("WX.redirect_uri");

    private static String redirect_invited_uri = ConfigHelper.getConfig().getString("WX.invited.redirect_uri");

    private static final String secret = ConfigHelper.getConfig().getString("WX.SECRET");



    /**
     * 获取code
     *
     * @return String
     */
    public String getWxCode(int type,String params) {
        String url = null;
        String redirect_uri_return = null;
        try {
            if (type==0){
                redirect_uri_return = URLEncoder.encode(redirect_uri,"utf-8");
                url = WX_URL + "?appid=" + APP_ID + "&redirect_uri=" + redirect_uri_return + "&response_type=" +
                        "code&scope=snsapi_userinfo#wechat_redirect";
            }else{
                redirect_uri_return = URLEncoder.encode(redirect_invited_uri,"utf-8");
                url = WX_URL + "?appid=" + APP_ID + "&redirect_uri=" + redirect_uri_return + "&response_type=" +
                        "code&scope=snsapi_userinfo"+"&state="+params+"#wechat_redirect";
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * 获取用户登陆token
     * @param code 之前获取的code
     * @return String
     */
    public String getLoginToken(String code){
        String url = ConfigHelper.getConfig().getString("WX.LOGIN.TOKEN")+"?appid="+APP_ID+"&secret="+secret+"&code="+code+"&grant_type="+"authorization_code";
        String message = this.sendGetMethod(url);
        return message;
    }

    /**
     * 获取用户信息
     * @param access_token 上一步拿到的用户token
     * @param openId 上一步拿到的用户唯一标识
     * @return json message
     */
    public String getUserInfo(String access_token,String openId){
        String url = ConfigHelper.getConfig().getString("WX.USER.INFO")+"?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
        String message = this.sendGetMethod(url);
        return message;
    }


    /**
     * 获取微信access_token(分享token非登陆token)
     * @return
     */
    public String getWxAccessToken() {
        String url = ConfigHelper.getConfig().getString("WX.GET.TOKEN.URL") + "?grant_type=client_credential" + "&appid=" + APP_ID + "&secret=" + secret;
        String message = this.sendGetMethod(url);
        return message;
    }

    /**
     *
     * @param wxAccessToken 微信获取微信access_token
     * @return JsapiTicket
     * @throws IOException 输入输出异常
     */
    public String getJsapiTicket(String wxAccessToken) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        @SuppressWarnings("unchecked")
        Map<String, Object> returnData = mapper.readValue(wxAccessToken, Map.class);
        String access_token = (String) returnData.get("access_token");
        String url = ConfigHelper.getConfig().getString("WX.GET.JS_API") + "?access_token=" + access_token + "&type=jsapi";
        String message = this.sendGetMethod(url);
        return message;
    }


    /**
     *
     * @param jsapiTicket jsapiTicket
     * @param url 加密页面
     * @param timestamp
     * @param nonceStr
     * @return
     */
    public String generateSign(String jsapiTicket, String url, long timestamp, String nonceStr) {
        String str ="jsapi_ticket="+jsapiTicket+"&noncestr="+nonceStr+"&timestamp="+timestamp+"&url="+url;
        String sign = DigestUtils.sha1Hex(str);
        return sign;
    }


    private String sendGetMethod(String url) {
        String message = null;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet
                    .openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout",
                    "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            System.setProperty("jsse.enableSNIExtension", "false");
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            message = new String(jsonBytes, "UTF-8");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

}
